<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-row>
      <el-table
        row-key="id"
        v-loading="formLoading"
        :data="tableData"
        :stripe="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学生姓名" align="center" prop="studentName" min-width="100" />
        <el-table-column label="电话号码" align="center" prop="studentPhoneNumber" min-width="150" />
      </el-table>
      <div style="margin-top: 10px; color: #606266">
        已选择 {{ checkedIds.length }} 个学生
      </div>
    </el-row>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading || checkedIds.length === 0"
      >
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {
  CourseStudentRegistFormApi
} from '@/api/train/coursestudentregistform'
import { Order, OrderApi } from '@/api/train/order'
import { CourseClassesApi } from '@/api/train/courseclasses'

/** 班级学生 表单 */
defineOptions({ name: 'CourseStudentRegistFormForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const tableRef = ref() // 表格 Ref
const tableData = ref<Order[]>([]) // 表格数据
const checkedIds = ref([]) // 多选结果
const classesId = ref();

/** 处理多选变化 */
const handleSelectionChange = (selection: any[]) => {
  checkedIds.value = selection.map((item) => item.id)
}

/** 加载学生数据 */
const loadStudentData = async (commId: number) => {
  formLoading.value = true
  try {
    // 这里需要根据实际API调用获取学生列表数据
    const data = await OrderApi.getOrderListByCommodityId(commId)
    tableData.value = data
  } catch (error) {
    console.error('加载学生数据失败:', error)
  } finally {
    formLoading.value = false
  }
}

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '添加学生'
  formType.value = 'create'
  classesId.value = id
  resetForm()

  // 加载学生列表数据
  try {
    const classInfo = await CourseClassesApi.getCourseClasses(Number.parseInt(id))
    await loadStudentData(classInfo.commodityId)
  } catch (e) {}

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (checkedIds.value.length === 0) {
    message.warning('请至少选择一个学生')
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    await CourseStudentRegistFormApi.createCourseStudentRegistFormList(classesId.value, checkedIds.value)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  checkedIds.value = []
  // 清除表格选择状态
  nextTick(() => {
    tableRef.value?.clearSelection()
  })
}
</script>
